package org.BiteTheDice;
import org.BiteTheDice.R;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.DialogInterface;

import com.facebook.android.*;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;

public class GameEndsActivity extends Activity implements OnClickListener{

	/**Facebook Global Stuff*/
	public static final String APP_ID = "162398780495208";
	private static final String FACEBOOK_PERMISSION = "publish_stream";
	private LoginButton mLoginButton;
	private Button mPostButton;
	private Facebook mFacebook;
	private Handler mHandler;
	private AsyncFacebookRunner mAsyncRunner;
	private String userName="I";
	public static boolean logedInFromPostClick=false;
	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.end_game);
		TextView view=(TextView) findViewById(R.id.gameScore);
		view.setText("Your Score is:\n"+BiteTheDice.currentScore);
		saveScores(BiteTheDice.currentScore);
		View newButton = findViewById(R.id.newGame);
		newButton.setOnClickListener(this);
		View backButton = findViewById(R.id.backMain);
		backButton.setOnClickListener(this);
		mPostButton = (Button) findViewById(R.id.postButton);
		mLoginButton = (LoginButton) findViewById(R.id.login);
		mFacebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(mFacebook);
		mHandler=new Handler();
		SessionStore.restore(mFacebook, this);
		SessionEvents.addAuthListener(new FacebookConnectListener());
		SessionEvents.addLogoutListener(new FacebookLogoutListener());
		mLoginButton.init(this, mFacebook, new String[]{FACEBOOK_PERMISSION});
		if (mFacebook.isSessionValid()){
			mAsyncRunner.request("me", new GetUserNameListener());
		}
		mPostButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (mFacebook.isSessionValid()){
					postMessageInThread();
				}
				else{
					logedInFromPostClick=true;
					mLoginButton.performClick();
				}
			}
		});
	}
	@Override
	protected void onResume() {
		super.onResume();
		Music.play(this, R.raw.menumusic);
	}

	@Override
	protected void onPause() {
		super.onPause();
		Music.stop(this);
	}

	/**
	 * Connect Buttons With XML's
	 */
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.newGame:
			openNewGameDialog();
			break;
		case R.id.backMain:
			Intent j = new Intent(this, BiteTheDice.class);
			startActivity(j);
			break;
		}

	}

	/**
	 * Opens Select Game type Menu 
	 */
	private void openNewGameDialog() {
		ColorAlertDialog.Builder dialog = new ColorAlertDialog.Builder(this, R.style.YellowAlertDialogTheme);
		dialog.setTitle("Game Type");
		dialog.setPositiveButton("Single Player", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialoginterface,
					int i) {
				startGame(0);	
			}
		});
		dialog.setNegativeButton("Two Players", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialoginterface,
					int i) {
				startGame(1);	
			}
		});	
		dialog.create();
		dialog.show();
	}

	/**
	 * Start Game
	 */

	private void startGame(int i) {
		if (i==0){
			RunGame.setNumPlayer(1);
			Intent j = new Intent(this, RunGame.class);
			startActivity(j);
		}
		else{
			//run multi player game...
			RunGame.setNumPlayer(2);
			Intent j = new Intent(this, RunGame.class);
			startActivity(j);
		}

	}

	protected void saveScores(int score){
		if (score<=BiteTheDice.SCORE9)
			return;
		ArrayList<Integer> scores=new ArrayList<Integer>();
		scores.add(score);
		scores.add(BiteTheDice.SCORE0);
		scores.add(BiteTheDice.SCORE1);
		scores.add(BiteTheDice.SCORE2);
		scores.add(BiteTheDice.SCORE3);
		scores.add(BiteTheDice.SCORE4);
		scores.add(BiteTheDice.SCORE5);
		scores.add(BiteTheDice.SCORE6);
		scores.add(BiteTheDice.SCORE7);
		scores.add(BiteTheDice.SCORE8);
		scores.add(BiteTheDice.SCORE9);


		Collections.sort(scores, new Intcomp());

		SharedPreferences preferences = getSharedPreferences(BiteTheDice.PREF_FILE_NAME,MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		int newScore=scores.get(0);
		BiteTheDice.SCORE0=newScore;
		editor.putInt("SCORE0", newScore); // value to store

		newScore=scores.get(1);
		BiteTheDice.SCORE1=newScore;
		editor.putInt("SCORE1", newScore); // value to store

		newScore=scores.get(2);
		BiteTheDice.SCORE2=newScore;
		editor.putInt("SCORE2", newScore); // value to store

		newScore=scores.get(3);
		BiteTheDice.SCORE3=newScore;
		editor.putInt("SCORE3", newScore); // value to store

		newScore=scores.get(4);
		BiteTheDice.SCORE4=newScore;
		editor.putInt("SCORE4", newScore); // value to store

		newScore=scores.get(5);
		BiteTheDice.SCORE5=newScore;
		editor.putInt("SCORE5", newScore); // value to store

		newScore=scores.get(6);
		BiteTheDice.SCORE6=newScore;
		editor.putInt("SCORE6", newScore); // value to store

		newScore=scores.get(7);
		BiteTheDice.SCORE7=newScore;
		editor.putInt("SCORE7", newScore); // value to store

		newScore=scores.get(8);
		BiteTheDice.SCORE8=newScore;
		editor.putInt("SCORE8", newScore); // value to store

		newScore=scores.get(9);
		BiteTheDice.SCORE9=newScore;
		editor.putInt("SCORE9", newScore); // value to store

		editor.commit();

	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
			Intent j = new Intent(this, BiteTheDice.class);
			startActivity(j);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}


	//*****************FACEBOOK STUFF***************/
	public class GetUserNameListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				JSONObject json = Util.parseJson(response);
				final String name = json.getString("name");
				userName=name.split(" ")[0];
			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
		}
	}

	public class FacebookConnectListener implements AuthListener {

		public void onAuthSucceed() {
			mAsyncRunner.request("me", new GetUserNameListener());
			if (logedInFromPostClick){
				postMessageInThread();
				logedInFromPostClick=false;
			}
			else{
				Context context = getApplicationContext();
				CharSequence text = "You have logged in!";
				int duration = Toast.LENGTH_SHORT;
				Toast toast = Toast.makeText(context, text, duration);
				toast.setGravity(Gravity.CENTER, 0, 180);
				toast.show();
			}
		}

		public void onAuthFail(String error) {
			Context context = getApplicationContext();
			CharSequence text = "Login Failed: " + error;
			int duration = Toast.LENGTH_SHORT;
			Toast toast = Toast.makeText(context, text, duration);
			toast.setGravity(Gravity.CENTER, 0,180);
			toast.show();
		}
	}

	public class FacebookLogoutListener implements LogoutListener {
		public void onLogoutBegin() {
			Context context = getApplicationContext();
			CharSequence text = "Logging out...";
			int duration = Toast.LENGTH_SHORT;
			Toast toast = Toast.makeText(context, text, duration);
			toast.setGravity(Gravity.CENTER, 0, 180);
			toast.show();
		}

		public void onLogoutFinish() {
			Context context = getApplicationContext();
			CharSequence text = "You have logged out!";
			int duration = Toast.LENGTH_SHORT;
			Toast toast = Toast.makeText(context, text, duration);
			toast.setGravity(Gravity.CENTER, 0, 180);
			toast.show();
		}
	}

	private void postMessageInThread() {	
		Thread t = new Thread() {		
			public void run() {
				try {	 
					postMessageOnWall(userName+" Just scored "+org.BiteTheDice.BiteTheDice.currentScore+
					" Points on Bite The Dice!\n Can you do better?");
					mHandler.post(mUpdateFacebookNotification);	
				} 
				catch (Exception ex) {			
					System.out.println("fail");
					mHandler.post(FailFacebookNotification);
				}	  
			}
		};
		t.start();
	}


	final Runnable mUpdateFacebookNotification = new Runnable() {   
		public void run() {      
			Context context = getApplicationContext();
			CharSequence text = "Post Succefully Posted!";
			int duration = Toast.LENGTH_SHORT;
			Toast toast = Toast.makeText(context, text, duration);
			toast.setGravity(Gravity.CENTER, 0, 180);
			toast.show();
		}  
	};
	final Runnable FailFacebookNotification = new Runnable() {   
		public void run() {      
			Context context = getApplicationContext();
			CharSequence text = "Failed to Connect to Facebook!";
			int duration = Toast.LENGTH_SHORT;
			Toast toast = Toast.makeText(context, text, duration);
			toast.setGravity(Gravity.CENTER, 0, 180);
			toast.show();
		}  
	};

	public void postMessageOnWall(String msg) {
		if (mFacebook.isSessionValid()){
			Bundle parameters = new Bundle();	  
			parameters.putString("message", msg);	  
			try {			
				String response = mFacebook.request("me/feed", parameters,"POST");		
				System.out.println(response);		
			} 
			catch (IOException e) {		
				e.printStackTrace();	
			}
		}
		else{
			logedInFromPostClick=true;
			mLoginButton.performClick();
		}
	}
}



